package com.yanhao

import android.app.Activity
import android.content.Context
import android.view.inputmethod.InputMethodManager
import java.util.*

class AppManager private constructor() {
    companion object {
        val instance: AppManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            AppManager()
        }
    }

    private var mActivities = Stack<Activity>()

    fun addActivity(act: Activity) {
        mActivities.add(act)
    }

    fun removeActivity(act: Activity) {
        hideSoftKeyBoard(act)
        act.finish()
        mActivities.remove(act)
    }

    fun removeAllActivity() {
        for (item in mActivities) {
            hideSoftKeyBoard(item)
            item.finish()
        }
        mActivities.clear()
    }

    fun hideSoftKeyBoard(act: Activity) {
        val localView = act.currentFocus
        localView?.let {
            val imm = act.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(localView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

}